package leetcode.easy.q28;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Q {
    public static void main(String[] args) {
        String a = "1aa2";
        String b = "aa2";
        log.info("{}", new Solution().strStr(a, b)==new Solution1().strStr(a,b));
    }
}

/**
 * 利用String的工具
 */
class Solution {
    public int strStr(String haystack, String needle) {
        if (haystack == null || needle == null) return -1;
        int firstChar = 0;
        while (!haystack.startsWith(needle, firstChar)) {
            if (haystack.length() - firstChar < needle.length()) return -1;
            firstChar++;
        }
        return firstChar;
    }
}
/**
 * 纯手工
 */
class Solution1 {
    public int strStr(String haystack, String needle) {
        if (haystack == null || needle == null) return -1;
        int firstChar = 0;
        while (!startsWith(haystack, needle, firstChar)) {
            if (haystack.length() - firstChar < needle.length()) return -1;
            firstChar++;
        }
        return firstChar;
    }

    private boolean startsWith(String source, String target, int offset) {
        int sourceLen = source.length();
        int targetLen = target.length();
        if (sourceLen - offset < targetLen) {
            return false;
        }
        char[] sourceChars = source.toCharArray();
        char[] targetChars = target.toCharArray();
        int to = 0;
        while (to < targetLen) {
            if (sourceChars[offset + to] != targetChars[to]) {
                return false;
            }
            to++;
        }
        return true;
    }
}